<template>
  <div class="upload-box">
    <el-upload
      class="upload"
      v-if="!$attrs.disabled"
      :class="$attrs.disabled?'upload-disabled':''"
      v-bind="$attrs"
      v-on="$listeners"
      :action="url"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :show-file-list="showFileList"
      :file-list="fileList"
      :headers="uploadHeaders"
      :on-progress="handleProgress"
      :before-remove="beforeRemove"
      :accept="$attrs.accept"
      :beforeUpload="beforeUpload"
      :on-exceed="handleExceed">
<!--      <el-button size="small" type="default" v-show="!$attrs.onlyOneFile" icon="el-icon-upload2">点击上传</el-button>-->
      <el-button size="small" type="default" icon="el-icon-upload2" :disabled="$attrs.disabled">点击上传</el-button>
      <div slot="tip" class="el-upload__tip" style="margin-left: 10px" v-if="$attrs.tip">{{$attrs.tip}}</div>
    </el-upload>
    <div :style="$attrs.style+';display:flex;'">
        <div class="file-list flex-lic" v-for="(item,index) of fileList" :key="index">
            <el-link @click="getPreviewUrl(item)" target="_blank">
                <svg-icon icon-class='upload-file' style="fill: white"/>
                {{item.name||item.fileName}}
            </el-link>
            <i class="el-icon-error delIcon" @click="removeFile(item)" v-if="(!$attrs.disabled) || (progress>0 && progress<100)"></i>
        </div>
    </div>
    <div class="file-list flex-lic progress-box" v-show="currentFileName">
     <div>
       <svg-icon icon-class='upload-file' style="fill: white"/>
       {{currentFileName}}
       <i class="el-icon-error delIcon" @click="removeFile(file)" v-if="(!$attrs.disabled) || (progress>0 && progress<100)"></i>
     </div>
      <div>
        <el-progress :percentage="progress" :color="customColors"></el-progress>
      </div>
    </div>
    <el-checkbox-group v-model="fileList"></el-checkbox-group>



<!--    预览pdf或者txt或者doc文件 start-->
    <el-dialog title="预览" :visible.sync="dialogVisible" v-if="dialogVisible" width="90%" height="600" append-to-body>
    </el-dialog>
<!--    预览pdf或者txt或者doc文件 end-->



  </div>
</template>

<script>
  import axios from 'axios'


  export default {
    name: "ZbFormUpload",
    directives: {},
    filters: {},
    mixins: [],
    model: {},
    props: {
      showFileList: Boolean,
      url: {
        type: String,
        default: `${process.env.VUE_APP_BASE_URL}${process.env.VUE_APP_BASE_API}/file/uploadFile`
      },
      previewOrdownload: {
        type: String,
        default: `download`// 下载还是预览，download 是下载，preview 是预览
      },
      value: {
        type: Array,
        default: () => ([])
      },
      previewUrl: {
        type: String,
        default: `${process.env.VUE_APP_BASE_URL}${process.env.VUE_APP_BASE_API}/file/image`
      },
      downUrl: {
        type: String,
        default: `${process.env.VUE_APP_BASE_URL}${process.env.VUE_APP_BASE_API}/file/downFile`
      },
      fileType: String,
      headers: {
        type: Object,
        default:() =>({})
      },
      listType: {
        type: String,
        default: 'text'
      },
      token:{
        type: String,
        default: 'token'
      },
      successStatus:{
          type: Number,
          default: 0
      },
      resDataMap:{
          type: [Object,Array],
          default: ()=>{
            return {
              status:'code',
              errorMsg:'msg',
              data:'data',
              fileName:'data.fileName',
              fileId:'data.fileId',
              id:'data.id',
              ocfId:'data.ocfId',
              name:'data.name',
            }
          }
      },
      // 返回结果如果少了一些字段，可以通过这个来进行映射，
      resultDataMap:{
          type: [Object],
          default: ()=>{
            return {}
          }
      },
    },
    data() {
      return {
        acceptString: '',
        fileList: [],
        file:{},
        uploadHeaders: {},
        progress: 0,   // 上传进度
        ifFileUploadEd:true,
        currentFileName: null, // 上传文件名称
        customColors: [
          {color: '#f56c6c', percentage: 20},
          {color: '#e6a23c', percentage: 40},
          {color: '#5cb87a', percentage: 60},
          {color: '#1989fa', percentage: 80},
          {color: '#6f7ad3', percentage: 100}
        ], // 进度条颜色,
        fileViewUrl:'',// 文件预览的url
        dialogVisible:false,
        parseFileType:'txt',
      }
    },
    watch: {
      fileList: {
        handler(val) {
          // this.$emit('input',val)
          // 注释掉否则会发生渲染缓慢的结果
          this.$emit('input',val)
          this.$emit('change',val)
        },
        deep: true
      },
      value: {
        handler(val) {
          this.fileList = val || []
        },
        deep: true,
        immediate: true
      }
    },
    created() {
      if(this.listType === 'picture') {
        this.acceptString = '.jpg,.jpeg,.png,.JPG,.JPEG,.PNG,.psd,.gif'
      } else {
        this.acceptString = ''
      }
      this.uploadHeaders = Object.assign(this.headers,{Authentication: this.token})
    },
    methods: {
      handleRemove(file) {
        this.ifFileUploadEd = false
        if (this.fileList && this.fileList.length){
          const fileId = file.id || file.response.data.id
          const index = this.fileList.findIndex(i => i.id === fileId)
          if (index !== -1) {
            this.fileList.splice(index,1)
          }
        }
      },
      removeFile(file) {
        this.beforeRemove(file).then(() => {
          this.handleRemove(file)
        })
      },
      toRawType(value) {
        return Object.prototype.toString.call(value).slice(8, -1)
      },
      getPreviewUrl(file) {
        // if (this.fileType === 'cad') {
        //   const { getDwgViewUrl } = require('@/utils/dwgUtils')
        //   window.open(getDwgViewUrl(file.ocfId || file.response.data.ocfId))
        // } else
          // 取消图纸在线查看 2019-12-13 09:35:23
          if (this.fileType === 'private' || this.fileType === 'cad') { // 下载改为window.open&&添加私有文件下载 updated 2019-10-10
          const fileId = file.id || file.response.data.id
          const url =`${this.downUrl}/${fileId}`
          axios({
            method: 'get',
            url: url,
            responseType: 'arraybuffer',
            headers: {
              Authentication: this.token,
              filename:'utf-8',
              ...this.headers
            }
          }).then(res => {
            let status = eval(`res.${this.resDataMap.status}`)
            let error = eval(`res.${this.resDataMap.err}`)
            let data = eval(`res.${this.resDataMap.data}`)
            const type = this.toRawType(data)
            if (type === 'Object' && status !== this.successStatus) {
              this.$message.error(error)
              return
            }
            const fileStr = res.headers['content-disposition']
            // const fileName = decodeURI(fileStr.substr(fileStr.indexOf('filename=')+9))
            const fileName = file.name
            let url = window.URL.createObjectURL(new Blob([data]))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            document.body.appendChild(link)
            link.setAttribute('download', fileName)
            link.target = '_blank'
            link.click()
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }).catch(error => {
            console.log(error)
          })
        }else {
          const fileId = file.id || file.response.data.id
          const suffixIndex=(file.name||file.fileName).lastIndexOf(".");
          const suffix= (file.name||file.fileName).toString().substring(suffixIndex+1).toUpperCase();
          if(this.previewOrdownload==='preview'){
            window.open(`${this.previewUrl}/${fileId}`)
          } else  if(this.previewOrdownload==='previewPdfDoc'){
            this.parseFileType = (file.name||file.fileName).toString().substring((file.name||file.fileName).toString().lastIndexOf(".")+1)
            this.dialogVisible = true
            this.fileViewUrl = `${this.downUrl}/${fileId}`
          } else {
            if(["BMP","JPG","JPEG","PNG","GIF"].includes(suffix)){
              window.open(`${this.previewUrl}/${fileId}`)
            } else {
              window.open(`${this.downUrl}/${fileId}`)
            }
          }
        }
      },
      handlePreview(file) {
        const fileId = file.id || file.response.data.id
        const url = `${this.previewUrl}/${fileId}`
        window.open(url,'_blank')
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 ${this.$attrs.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file) {
        return this.$confirm(`确定移除 ${ (file.name||file.fileName) }？`);
      },
      beforeUpload(file) {
        this.file = file
        this.ifFileUploadEd = true
        this.$emit('beforeUpload',file)
      },
      handleSuccess(response) {
          let status = eval(`response.${this.resDataMap.status}`)
          let id = eval(`response.${this.resDataMap.id}`)
          let fileId = eval(`response.${this.resDataMap.fileId}`)
          let fileName = eval(`response.${this.resDataMap.fileName}`)
          let fileSize_ = eval(`response.${this.resDataMap.fileSize}`)
          let ocfId = eval(`response.${this.resDataMap.ocfId}`)
          let name = eval(`response.${this.resDataMap.name}`)
          let data = eval(`response.${this.resDataMap.data}`)
          let errorMsg = eval(`response.${this.resDataMap.errorMsg}`)
        try {
          if ( this.ifFileUploadEd && status === this.successStatus) {
            // console.log(111111)
            this.progress = 100
            const index = this.fileList.findIndex(i => i.id === id || fileId === i.id)
            if (index === -1) {
              let fileSize = 0
              if (response && data && fileSize) fileSize = fileSize_
              let keys = Object.keys(this.resultDataMap)
              let result = {}
              for (let i = 0; i < keys.length; i++) {
                result[keys[i]] = data[keys[i]]
              }
              let p = {id: id || fileId, name: fileName || name, ocfId: ocfId,fileSize:fileSize,...result}
              if (this.$attrs.appendField && (this.$attrs.appendField instanceof Array)&& this.$attrs.appendField.length){
                for (let k in this.$attrs.appendField){
                  p[this.$attrs.appendField[k]] = data[this.$attrs.appendField[k]]
                }
              }
              this.fileList.push(p)
            }
          } else {
            this.$message.error(errorMsg)
          }
        }catch (e) {
          console.log(e)
        }
        this.currentFileName = null
        this.progress = 0
        // 成功后自动滚动到最后
        let w = document.querySelector('.upload-box').scrollWidth
        document.querySelector('.upload-box').scrollLeft = w
        this.$emit('uploadSuccess',this.value,response)
      },
      handleError(err) {
        console.log(err)
        this.$message.error("文件上传失败")
        this.currentFileName = null
        this.progress = 0
      },
      handleProgress(event, file) {
        if (!this.ifFileUploadEd){
          this.currentFileName = null
          this.progress = 0
          this.$emit('uploadSuccess',this.value,file)
          return
        }
        // console.log(this.progress)
        if (this.progress === 0) {
          this.currentFileName = file.name
        }
        let progress = event.percent.toFixed(2)
        if (progress >= 99.99) {
          progress = 99.99
        }
        this.progress = parseFloat(progress)
      }
    },
  }
</script>

<style scoped lang="scss">
  .upload-box {
    width: 100%;
    overflow-x: scroll;
    height: auto;
    display: -webkit-box !important;
    .file-list {
      margin-right: 20px;
      white-space: nowrap;
      i {
        vertical-align: middle;
      }
    }
    .progress-box {
      min-width: 160px;
      overflow: hidden;
      div {
        width: 99%;
        text-align: left;
      }
    }
    .upload {
      /*display: flex;*/
      ::v-deep .el-upload-list {
        display: flex;
        align-items: center;
        .el-upload-list__item {
          margin-top: 0;
        }
      }
      ::v-deep .el-icon-close-tip {
        display: none !important;
      }
    }
    .upload-disabled {
      ::v-deep .el-upload {
        display: none;
      }
    }
    &::-webkit-scrollbar {
      width: 10px;
      height: 6px;
    }
    &::-webkit-scrollbar-thumb {
      border-radius: 10px;
      -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
      background: rgba(144,147,153,.3);
      :hover {
        background: rgba(144,147,153,.5)
      }
    }
  }
  .el-form-item__content::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  .el-form-item__content::-webkit-scrollbar-track {
    background: rgb(239, 239, 239);
    border-radius: 2px;
  }

  .el-form-item__content::-webkit-scrollbar-thumb {
    background: #bfbfbf;
    border-radius: 10px;
  }

  .el-form-item__content::-webkit-scrollbar-thumb:hover {
    background: #333;
  }

  .el-form-item__content::-webkit-scrollbar-corner {
    background: #179a16;
  }
</style>
